/**
 * 员工管理模块
 * 负责管理员工信息的增删改查，以及与部门模块的联动
 */

// 定义状态
const state = {
  list: [] // 员工列表
}

// 定义mutation
const mutations = {
  // 设置员工列表
  SET_LIST(state, list) {
    state.list = list
  },
  // 添加新员工
  ADD_EMPLOYEE(state, emp) {
    state.list = [...state.list, emp]
  },
  // 编辑员工信息
  EDIT_EMPLOYEE(state, emp) {
    const idx = state.list.findIndex(e => e.id === emp.id)
    if (idx !== -1) state.list.splice(idx, 1, emp)
  },
  // 删除员工
  DELETE_EMPLOYEE(state, id) {
    state.list = state.list.filter(e => e.id !== id)
  }
}

// 定义action
const actions = {
  // 获取员工列表
  fetchList({ commit, state }) {
    return new Promise((resolve) => {
      // 如果已有数据，直接使用
      if (state.list && state.list.length > 0) {
        console.log('employee.js: state already populated, using existing data')
        resolve()
        return
      }

      // 模拟API请求，获取初始数据
      setTimeout(() => {
        const initialData = [
          {
            id: 1,
            name: '张三',
            department: '技术部',
            position: '经理',
            email: 'zhangsan@example.com',
            phone: '13888888888',
            status: '在职'
          },
          {
            id: 2,
            name: '李四',
            department: '人事部',
            position: '经理',
            email: 'lisi@example.com',
            phone: '13999999999',
            status: '在职'
          },
          {
            id: 3,
            name: '王五',
            department: '财务部',
            position: '经理',
            email: 'wangwu@example.com',
            phone: '13777777777',
            status: '在职'
          },
          {
            id: 4,
            name: '赵六',
            department: '市场部',
            position: '经理',
            email: 'zhaoliu@example.com',
            phone: '13666666666',
            status: '在职'
          },
          {
            id: 5,
            name: '薛馨儿',
            department: '技术部',
            position: '员工',
            email: 'xxe@example.com',
            phone: '199988666666',
            status: '在职'
          }
        ]

        commit('SET_LIST', initialData)
        console.log('employee.js: fetched initial data with 张三, 李四, 王五, 赵六')
        resolve()
      }, 500)
    })
  },

  // 添加新员工
  addEmployee({ commit, state, dispatch }, emp) {
    // 生成新员工ID
    const newEmp = {
      ...emp,
      id: state.list.length ? Math.max(...state.list.map(e => e.id)) + 1 : 1
    }

    commit('ADD_EMPLOYEE', newEmp)

    // 如果职位是"经理"，更新对应部门的主管
    if (newEmp.position === '经理') {
      dispatch('department/updateManager', { departmentName: newEmp.department, manager: newEmp.name }, { root: true })
    }

    // 更新部门人数
    dispatch('department/incrementEmployeeCount', newEmp.department, { root: true })

    return Promise.resolve(newEmp)
  },

  // 编辑员工信息
  editEmployee({ commit, state, dispatch }, emp) {
    return new Promise((resolve, reject) => {
      const oldEmp = state.list.find(e => e.id === emp.id)

      // 如果部门变更，更新旧部门和新部门的人数
      if (oldEmp && oldEmp.department !== emp.department) {
        dispatch('department/decrementEmployeeCount', oldEmp.department, { root: true })
        dispatch('department/incrementEmployeeCount', emp.department, { root: true })
      }

      // 如果职位变为"经理"，更新部门主管
      if (emp.position === '经理') {
        dispatch('department/updateManager', { departmentName: emp.department, manager: emp.name }, { root: true })
      } else if (oldEmp && oldEmp.position === '经理' && emp.position !== '经理') {
        dispatch('department/updateManager', { departmentName: oldEmp.department, manager: '' }, { root: true })
      }

      commit('EDIT_EMPLOYEE', emp)
      resolve(emp)
    })
  },

  // 删除员工
  deleteEmployee({ commit, state, dispatch }, id) {
    return new Promise((resolve) => {
      const emp = state.list.find(e => e.id === id)
      if (!emp) {
        resolve()
        return
      }

      // 如果删除的是经理，清空该部门主管
      if (emp.position === '经理') {
        dispatch('department/updateManager', { departmentName: emp.department, manager: '' }, { root: true })
      }

      // 减少部门人数
      dispatch('department/decrementEmployeeCount', emp.department, { root: true })

      commit('DELETE_EMPLOYEE', id)
      resolve()
    })
  }
}

// 导出模块
export default {
  namespaced: true, // 启用命名空间
  state,
  mutations,
  actions
}